#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复JSON文件编码问题的脚本
"""

import os
import sys

def detect_encoding(file_path):
    """检测文件编码"""
    try:
        # 尝试不同的编码
        encodings = ['utf-8', 'utf-8-sig', 'gbk', 'gb2312', 'utf-16', 'utf-16le', 'utf-16be']
        
        for encoding in encodings:
            try:
                with open(file_path, 'r', encoding=encoding) as f:
                    content = f.read()
                    print(f"成功使用 {encoding} 编码读取文件")
                    return encoding, content
            except UnicodeDecodeError:
                continue
        
        print("无法检测到正确的编码格式")
        return None, None
        
    except Exception as e:
        print(f"检测编码时出错: {e}")
        return None, None

def fix_encoding(file_path):
    """修复文件编码为UTF-8"""
    try:
        # 检测当前编码
        encoding, content = detect_encoding(file_path)
        
        if encoding is None:
            print("无法检测文件编码，尝试二进制读取")
            # 尝试二进制读取
            with open(file_path, 'rb') as f:
                raw_content = f.read()
            
            # 尝试去除BOM
            if raw_content.startswith(b'\xef\xbb\xbf'):
                content = raw_content[3:].decode('utf-8')
                print("检测到UTF-8 BOM，已去除")
            elif raw_content.startswith(b'\xff\xfe'):
                content = raw_content[2:].decode('utf-16le')
                print("检测到UTF-16LE BOM，已转换")
            elif raw_content.startswith(b'\xfe\xff'):
                content = raw_content[2:].decode('utf-16be')
                print("检测到UTF-16BE BOM，已转换")
            else:
                # 尝试不同的编码
                for enc in ['utf-8', 'gbk', 'gb2312']:
                    try:
                        content = raw_content.decode(enc)
                        print(f"使用 {enc} 编码成功解码")
                        break
                    except UnicodeDecodeError:
                        continue
                else:
                    print("无法解码文件内容")
                    return False
        
        # 备份原文件
        backup_path = file_path + '.backup'
        if not os.path.exists(backup_path):
            os.rename(file_path, backup_path)
            print(f"已备份原文件到 {backup_path}")
        
        # 以UTF-8编码重新写入
        if content is not None:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
        else:
            print("内容为空，无法写入文件")
            return False
        
        print(f"文件 {file_path} 已转换为UTF-8编码")
        return True
        
    except Exception as e:
        print(f"修复编码时出错: {e}")
        return False

def main():
    """主函数"""
    files_to_fix = ['data.json', 'data_types.json', 'data_commodity.json']
    
    for file_name in files_to_fix:
        if os.path.exists(file_name):
            print(f"\n处理文件: {file_name}")
            print("=" * 50)
            
            # 检测编码
            encoding, _ = detect_encoding(file_name)
            if encoding:
                print(f"当前编码: {encoding}")
            
            # 修复编码
            if fix_encoding(file_name):
                print(f"✅ {file_name} 编码修复成功")
            else:
                print(f"❌ {file_name} 编码修复失败")
        else:
            print(f"文件 {file_name} 不存在")

if __name__ == "__main__":
    main() 